package com.gitee.cui.security.crypto;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Hash加密算法演示
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/4 13:45
 **/
@Slf4j
public class HashCrypto {

    public static void main(String[] args) {
        // 需要加密的字符串
        String plain = "123456";
        // 加密后的字符串
        String message = HashCrypto.encrypt(plain);
        log.info("加密后的字符串：{}", message);

        // 第二次加密后的字符串
        String message2 = HashCrypto.encrypt(plain);
        log.info("加密后字符串：{}, \n 是否一致：{}", message2, message2.equals(message));

        // 再次验证不同的原始字符串加密后的结果是否一致
        String text = "654321";
        String msg = HashCrypto.encrypt(text);
        log.info("不同初始字符串加密后：{}, \n 是否一致：{}", msg, msg.equals(message));
    }

    /**
     * 对字符串进行加密
     * @param plain 需要加密的字符串
     * @return 加密后的字符串
     */
    private static String encrypt(String plain) {
        StringBuffer sb = new StringBuffer();
        try {
            // MD5
            // MessageDigest digest = MessageDigest.getInstance("MD5");
            // SHA-1
            // MessageDigest digest = MessageDigest.getInstance("SHA-1");
            // SHA-256
            // MessageDigest digest = MessageDigest.getInstance("SHA-256");
            // SHA-512
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] bytes = digest.digest(plain.getBytes(StandardCharsets.UTF_8));
            for (int i = 0; i < bytes.length; i++) {
                // 获取16进制字符串
                String hexStr = Integer.toHexString((0x000000FF & bytes[i]) | 0xFFFFFF00);
                log.debug("hexString: {}, 第6位之后：{}", hexStr, hexStr.substring(6));
                sb.append(hexStr.substring(6));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
}
